package com.lzjn.code.web.service.impl;

import com.lzjn.code.common.base.BaseDao;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.List;

@Component
public class InitDBServiceImpl extends BaseDao implements ApplicationListener<ApplicationStartedEvent> {

    private static final Logger log = LoggerFactory.getLogger(InitDBServiceImpl.class);

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        this.createTable();
    }

    private void createTable() {
        Connection conn = getConnection();
        Statement ps = null;

        try {
            String driverName = conn.getMetaData().getDriverName();
            log.info("DB type is {}", driverName);
            if(driverName.contains("SQLite")) {
                Resource resource = new ClassPathResource("init/db-sqlite.sql");
                List<String> lines = IOUtils.readLines(resource.getInputStream(), StandardCharsets.UTF_8);
                StringBuilder initSql = new StringBuilder();
                for(String line : lines) {
                    initSql.append(line);
                }
                ps = conn.createStatement();
                String[] sqlList = initSql.toString().split(";");
                for(String sql : sqlList) {
                    ps.execute(sql);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if(ps != null) {
                    ps.close();
                }
                if(conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
